<?php
    define('CONFIG_FILE',true);
    include '../config.php';
    
    define('DB_FILE',true);
    require_once '../Tool/DB/SqlDBManager.class.php';

    session_start();
    if (empty($_SESSION["userType"])) {
        $url="../Index.php";
		include_once '../Tool/Common/Redirect.php';
		exit();
    }

    if($_SESSION["userType"]=="Therapy Assistant"){
        $url="../Index.php";
		include_once '../Tool/Common/Redirect.php';
		exit();
    }
    
    $sqlDBManager = new SqlDBManager();

    $Username = $_REQUEST['Username'];
    $UserType = $_REQUEST['UserType'];
    $StaffName = $_REQUEST['StaffName'];
    $centreId=$_REQUEST['CentreId'];
    $ContactNumber = $_REQUEST['ContactNumber'];
    $Email = $_REQUEST['Email'];

    $sqlDBManager = new SqlDBManager();

    $sql = "SELECT * from User where Username=?";
    $parameters = array($Username);
    $res=$sqlDBManager->queryRow($sql,$parameters);

    if(!empty($res)){
        $UsernameExisted=$res['Username'];
        $UserTypeExisted=$res['UserType'];
        $StaffNameExisted=$res['StaffName'];
        $centreIdExisted=$res['CentreId'];
        $ContactNumberExisted=$res['ContactNumber'];
        $EmailExisted=$res['Email'];

        //If no changes, return ture else execute update statement
        if($Username==$UsernameExisted&&$UserType==$UserTypeExisted&&$StaffName==$StaffNameExisted&&$centreId==$centreIdExisted&&$ContactNumber==$ContactNumberExisted&&$Email==$EmailExisted){
            echo json_encode(array('success'=>true));   
        }else{

            if ($centreId == 0) {//User has been updated but centre has not been changed
                $sql = "UPDATE user SET UserType=?,StaffName=?, ContactNumber=?,Email=? WHERE Username=?";
                $parameters = array($UserType,$StaffName,$ContactNumber,$Email,$Username);
            	$res=$sqlDBManager->execute_dml($sql,$parameters);

                if($res>0){
                    echo json_encode(array('success' => true));
                }else{
                    echo json_encode(array('msg' => 'Update user account failed due to database error.'));
                }
            }else {
                $sql = "UPDATE user SET UserType=?,StaffName=?,CentreId =?, ContactNumber=?,Email=? WHERE Username=?";
                $parameters = array($UserType,$StaffName,$centreId,$ContactNumber,$Email,$Username);
            	$res=$sqlDBManager->execute_dml($sql,$parameters);

                if ($res>0) {
                    echo json_encode(array('success' => true));
                } else {
                    echo json_encode(array('msg' => 'Update user account failed due to database error.'));
                }
            }
        }
    }
    //close connection
    $sqlDBManager->close_connect();
?>